<template>
  <div class="live-container">
    <profile-header />
    <a-card :bordered="false">
      <!-- 主播界面 -->
      <template v-if="isStreamer">
        <a-tabs v-model:activeKey="activeTabKey">
          <a-tab-pane key="liveSettings" tab="开播设置">
            <a-form :model="formState" :labelCol="{ span: 2 }">
              <!-- 赛事选择 -->
              <a-form-item label="赛事" required>
                <template v-if="formState.liveStatus === 'live'">
                  <span>{{ formState.selectedEventText }}</span>
                </template>
                <template v-else>
                  <a-cascader
                    v-model:value="formState.selectedEvent"
                    :options="options"
                    :load-data="loadData"
                    placeholder="请选择赛事"
                    change-on-select
                  />
                </template>
              </a-form-item>

              <!-- 直播标题 -->
              <a-form-item label="直播标题" required>
                <template v-if="formState.liveStatus === 'live'">
                  <span>{{ formState.liveTitle }}</span>
                </template>
                <template v-else>
                  <a-input
                    v-model:value="formState.liveTitle"
                    placeholder="请输入直播标题"
                    style="width: 300px"
                  />
                </template>
              </a-form-item>

              <!-- 直播封面上传 -->
              <a-form-item label="直播封面">
                <div class="custom-upload">
                  <div v-if="!uploadedFile" class="upload-trigger" @click="triggerFileInput">
                    <plus-outlined />
                    <div style="margin-top: 8px">上传</div>
                  </div>
                  <div v-else class="preview-container">
                    <img :src="uploadedFile.room_img" alt="预览图" class="preview-image" />
                    <div class="preview-actions">
                      <a-button type="link" @click="removeFile">删除</a-button>
                    </div>
                  </div>
                  <input
                    type="file"
                    ref="fileInput"
                    style="display: none"
                    @change="handleFileChange"
                    accept="image/png,image/jpeg"
                  />
                </div>
                <div class="ant-upload-hint">支持png、jpg格式，图片大小不超过5M</div>
              </a-form-item>

              <!-- 直播状态显示 -->
              <a-form-item label="直播状态">
                <a-tag value="notStarted" v-show="formState.liveStatus === 'notStarted'"
                  >未开播</a-tag
                >

                <a-tag color="success" value="live" v-show="formState.liveStatus === 'live'"
                  >已开播</a-tag
                >
              </a-form-item>
              <!-- 推流链接和播流链接展示 -->
              <a-form-item v-if="formState.liveStatus === 'live'" label="推流链接">
                <a-input v-model:value="formState.pushAddr" readonly />
              </a-form-item>
              <a-form-item v-if="formState.liveStatus === 'live'" label="播放链接">
                <a-input v-model:value="formState.playAddr.hd_flv" readonly />
              </a-form-item>
              <!-- 开播/结束直播按钮 -->
              <a-form-item>
                <div style="width: 400px; display: flex; justify-content: center">
                  <a-space>
                    <a-button
                      type="primary"
                      v-if="formState.liveStatus === 'notStarted'"
                      @click="submitSettings"
                      :style="{
                        width: '110px',
                        height: '36px',
                        background: 'linear-gradient(270deg, #16B13A 0%, #80E197 100%)',
                        borderRadius: '20px',
                        border: 'none'
                      }"
                    >
                      开播
                    </a-button>
                    <a-button
                      v-if="formState.liveStatus === 'live'"
                      type="primary"
                      @click="endLive"
                      :style="{
                        width: '110px',
                        height: '36px',
                        background: 'linear-gradient(270deg, #16B13A 0%, #80E197 100%)',
                        borderRadius: '20px',
                        border: 'none'
                      }"
                    >
                      结束直播
                    </a-button>
                  </a-space>
                </div>
              </a-form-item>
            </a-form>
          </a-tab-pane>
          <!-- 可以在此添加更多的标签页 -->
        </a-tabs>
      </template>

      <!-- 非主播界面 -->
      <template v-else>
        <div class="not-streamer-message">
          <a-result
            status="info"
            title="暂不是主播"
            sub-title="您目前还不是主播,无法使用开播功能。"
          >
            <template #extra>
              <a-button
                :style="{
                  background: 'linear-gradient(270deg, #16B13A 0%, #80E197 100%)',
                  border: 'none'
                }"
                type="primary"
                @click="applyForStreamer"
                >申请成为主播</a-button
              >
            </template>
          </a-result>
        </div>
      </template>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { openLiveAPI, closeLiveAPI, getUserLiveInfoAPI } from '@/api/user'
import { getAllScheduleList } from '@/api/match'
import ProfileHeader from './profileHeader.vue'
import axios from 'axios'
import dayjs from 'dayjs'
import { decompressData } from '@/utils/dataProcessing'
import { userStore } from '@/stores/user'

// 使用 userStore
const store = userStore()

// 计算属性：判断用户是否为主播
const isStreamer = computed(() => store.userInfo?.isAnchor || false)

// 当前激活的标签页
const activeTabKey = ref('liveSettings')

// 表单状态
const formState = reactive({
  selectedEvent: '',
  selectedEventText: '',
  liveTitle: '',
  liveStatus: 'notStarted',
  pushAddr: '', // 推流链接
  playAddr: {} // 播流链接
})

// 上传文件相关
const uploadedFile = ref(null)
const fileInput = ref(null)

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value?.click()
}

// 处理文件变更
const handleFileChange = async (event: Event) => {
  const file = (event.target as HTMLInputElement).files?.[0]
  if (file) {
    // 文件大小检查
    if (file.size > 6 * 1024 * 1024) {
      message.error('文件大小不能超过6M')
      return
    }

    const formData = new FormData()
    formData.append('file', file)
    formData.append('token', '22ab27409e8a49d7acf160057a2f0cde')

    try {
      // 上传文件到服务器
      const response = await axios.post('https://api.superbed.cn/upload', formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })

      uploadedFile.value = {
        name: file.name,
        room_img: response.data.url
        // response: response.data
      }

      message.success('上传成功')
    } catch (error) {
      message.error('上传失败，请重试')
      console.error(error)
      // 重置文件输入，允许重新选择同一文件
      if (fileInput.value) {
        fileInput.value.value = ''
      }
    }
  }
}

// 移除已上传的文件
const removeFile = () => {
  uploadedFile.value = null
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

// 提交直播设置
const submitSettings = () => {
  // 表单验证
  if ((!formState.selectedEvent && formState.liveStatus !== 'live') || !formState.liveTitle || !uploadedFile.value.room_img) {
    message.error('请填写所有必填项并上传直播封面')
    return
  }

  const submitData = {
    title: formState.liveTitle,
    roomImg: uploadedFile.value ? uploadedFile.value.room_img : '',
    matchId:
      formState.liveStatus === 'live'
        ? undefined
        : formState.selectedEvent[formState.selectedEvent.length - 1],
    matchType: formState.liveStatus === 'live' ? undefined : formState.selectedEvent[0]
  }

  console.log('提交的数据:', submitData)

  // 调用开播API
  openLiveAPI(submitData)
    .then((res) => {
      console.log('操作响应:', res)
      message.success('开播成功')
      formState.liveStatus = 'live'
      formState.pushAddr = res.data.live_detail.stream_info.pushAddr // 保存推流链接
      formState.playAddr = res.data.live_detail.stream_info.playAddr // 保存播流链接
      fetchLiveInfo() // 重新获取直播信息
    })
    .catch((err) => {
      console.error('操作错误:', err)
      message.error('开播失败: ' + (err.msg || '未知错误'))
    })
}

// 结束直播
const endLive = () => {
  closeLiveAPI({})
    .then((res) => {
      console.log('结束直播响应:', res)
      message.success('直播已结束')
      formState.liveStatus = 'notStarted'
      fetchLiveInfo() // 重新获取直播信息
    })
    .catch((err) => {
      console.error('结束直播错误:', err)
      message.error('结束直播失败: ' + (err.msg || '未知错误'))
    })
}

// 获取直播信息
const fetchLiveInfo = async () => {
  try {
    const response = await getUserLiveInfoAPI({})
    // 更新表单状态
    formState.liveTitle = response.data.stream_info.liveTitle
    formState.liveStatus = response.data.stream_info.status === 1 ? 'live' : 'notStarted'
    formState.pushAddr = response.data.stream_info.pushAddr // 保存推流链接
    formState.playAddr = response.data.stream_info.playAddr // 保存播流链接

    if (response.data.match_info?.match_id) {
      formState.selectedEvent = null
      formState.selectedEventText = `${response.data.match_info.title} - ${response.data.match_info.home_team.name} vs ${response.data.match_info.guest_team.name}`
    }

    // 处理直播封面
    if (response.data.room_img) {
      uploadedFile.value = {
        name: 'cover.jpg',
        room_img: response.data.room_img
      }
    } else {
      uploadedFile.value = null
    }
  } catch (error) {
    message.error('获取直播间详情失败')
    console.error(error)
  }
}

// 获取用户状态
const fetchUserStatus = async () => {
  try {
    await store.getUserInfo()
  } catch (error) {
    console.error('获取用户状态失败', error)
    message.error('获取用户状态失败')
  }
}

// 申请成为主播
const applyForStreamer = () => {
  message.info('请联系客服申请成为主播')
}

// 组件挂载时执行
onMounted(() => {
  fetchUserStatus()
  if (isStreamer.value) {
    fetchLiveInfo()
  }
})

// 赛事选择器选项
const options = ref([
  { value: 1, label: '足球', isLeaf: false },
  { value: 2, label: '篮球', isLeaf: false }
])

// 加载赛事数据
const loadData = (selectedOptions) => {
  const targetOption = selectedOptions[selectedOptions.length - 1]
  targetOption.loading = true

  if (selectedOptions.length === 1) {
    // 加载日期选项
    const dateOptions = []
    for (let i = 0; i < 8; i++) {
      const date = dayjs().add(i, 'day')
      dateOptions.push({
        value: date.format('YYYY-MM-DD'),
        label: date.format('YYYY-MM-DD'),
        isLeaf: false
      })
    }
    targetOption.children = dateOptions
    targetOption.loading = false
  } else if (selectedOptions.length === 2) {
    // 加载具体赛事
    const sportId = selectedOptions[0].value
    const date = selectedOptions[1].value
    getAllScheduleList({ sportId, matchDay: date })
      .then((res) => {
        if (res.code === 200) {
          let data = decompressData(res.data)
          const matchOptions = data.map((match) => ({
            value: match.id,
            label: `${match.title}-${match.home_team.name} vs ${match.guest_team.name}`,
            isLeaf: true
          }))
          targetOption.children = matchOptions
        }
      })
      .catch((err) => {
        console.error('获取赛事列表失败', err)
        message.error('获取赛事列表失败')
      })
      .finally(() => {
        targetOption.loading = false
      })
  }
}
</script>

<style lang="scss" scoped>
:deep(.ant-tabs-nav) {
  margin-bottom: 20px;

  .ant-tabs-ink-bar {
    background-color: #16b13a;
  }

  .ant-tabs-tab {
    color: #333;

    &.ant-tabs-tab-active {
      .ant-tabs-tab-btn {
        color: #16b13a;
      }
    }
  }
}
.live-container {
  .ant-upload-hint {
    font-size: 12px;
    color: rgba(0, 0, 0, 0.45);
  }

  .ant-btn-primary {
    color: #ffffff !important;
  }

  .custom-upload {
    width: 200px;
    // height: 104px;
    height: 200px;
    border: 1px dashed #d9d9d9;
    border-radius: 8px;
    margin-top: 10px;
    cursor: pointer;
    transition: border-color 0.3s;

    &:hover {
      border-color: #16b13a;
    }

    .upload-trigger {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      height: 100%;
    }

    .preview-container {
      position: relative;
      width: 100%;
      height: 100%;

      .preview-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-radius: 8px;
      }

      .preview-actions {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: rgba(0, 0, 0, 0.45);
        padding: 4px;
        text-align: center;
      }
    }
  }
}

.not-streamer-message {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}
</style>
